package com.DosonLeung.homeschoolcommunication.Controllers;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.DosonLeung.homeschoolcommunication.Constant.UrlConstant;
import com.DosonLeung.homeschoolcommunication.R;
import com.DosonLeung.homeschoolcommunication.Utils.NetWorkUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by dosonleung on 12/14/14.
 */
public class ReadActivity extends Activity{

    Activity self = this;
    String cid;
    String time;

    LinearLayout backBt;
    TextView readSum;
    ListView readList;
    TextView unreadSum;
    ListView unreadList;
    ImageView refresh;
    ProgressDialog pd;

    SimpleAdapter readAdadpter;
    SimpleAdapter unreadAdapter;

    int readRegister = 0;
    int unreadRegister = 0;
    JSONObject readJSONObject;
    ArrayList<Map<String,String>> readArray;
    ArrayList<Map<String,String>> unreadArray;

    final Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            /*0x200获取阅读列表成功
            *0x404网络超时
            */
            switch (msg.what) {
                case 0x200:
                    stopReflashDialog();
                    initList();
                    break;
                case 0x404:
                    stopReflashDialog();
                    Toast.makeText(self,"网络超时",Toast.LENGTH_SHORT).show();
                    break;
                case 0x500:
                    stopReflashDialog();
                    Toast.makeText(self,"运行时错误",Toast.LENGTH_SHORT).show();
                    self.finish();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.read_activity);
        initPara();
        initWidget();
        getList(mHandler);
    }

    private void initPara(){
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        cid = bundle.getString("cid");
        time = bundle.getString("time");
    }

    private void initWidget(){
        backBt = (LinearLayout) findViewById(R.id.read_back_btn);
        refresh = (ImageView) findViewById(R.id.refresh_readlist);
        readSum = (TextView) findViewById(R.id.read_sum);
        readList = (ListView) findViewById(R.id.read_list);
        unreadSum = (TextView) findViewById(R.id.unread_sum);
        unreadList = (ListView) findViewById(R.id.unread_list);
        backBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pressBack(view);
            }
        });
        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pressRefresh(view);
            }
        });
    }

    private void initList(){
        try {
            JSONArray read_status = readJSONObject.getJSONArray("read_status");
            if(readArray==null)
                readArray = new ArrayList<Map<String, String>>();
            if(unreadArray==null)
                unreadArray = new ArrayList<Map<String, String>>();
            int size = read_status.length();
            JSONObject jsonObject;
            Map<String,String> item;
            for(int i = 0;i < size;i++){
                jsonObject = read_status.getJSONObject(i);
                item = new HashMap<String, String>();
                item.put("name",jsonObject.getString("name"));
                item.put("phone",jsonObject.getString("phone"));
                if(jsonObject.get("status").equals("1")){
                    readArray.add(item);
                    readRegister++;
                }else{
                    unreadArray.add(item);
                    unreadRegister++;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        display();
        initListener();
    }

    private void display(){
        int sum = readRegister +unreadRegister;
        readSum.setText("已阅读："+String.valueOf(readRegister)+"/"+String.valueOf(sum));
        unreadSum.setText("未阅读："+String.valueOf(unreadRegister)+"/"+String.valueOf(sum));
        readAdadpter = new SimpleAdapter(self,readArray,R.layout.read_item, new String[]{"name"}, new int[]{R.id.read_name});
        unreadAdapter = new SimpleAdapter(self,unreadArray,R.layout.read_item, new String[]{"name"}, new int[]{R.id.read_name});
        readList.setAdapter(readAdadpter);
        unreadList.setAdapter(unreadAdapter);
        fixListViewHeight(readList);
        fixListViewHeight(unreadList);
    }

    private void initListener(){
        readList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String strMobile = readArray.get(i).get("phone");
                //此处应该对电话号码进行验证。。
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + strMobile));
                startActivity(intent);
            }
        });
        unreadList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String strMobile = unreadArray.get(i).get("phone");
                //此处应该对电话号码进行验证。。
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + strMobile));
                startActivity(intent);
            }
        });
    }

    private void getList(final Handler mhandler){
        showReflashDialog("加载中");
        new Thread() {
            @Override
            public void run() {
                Message msg = new Message();
                try {
                    String readString = NetWorkUtil.httpGet(String.format(UrlConstant.getReadUrl,cid,time));
                    if(readString!=null){
                        readJSONObject = new JSONObject(readString);
                        msg.what = 0x200;
                    }else{
                        msg.what = 0x404;
                    }
                    mhandler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                    mhandler.sendEmptyMessage(0x500);
                }
            }
        }.start();
    }

    private void reLoad(final Handler mHandler){
        readRegister = 0;
        unreadRegister = 0;
        readArray.clear();
        unreadArray.clear();
        getList(mHandler);
    }

    private void pressBack(View v){
        self.finish();
    }

    private void pressRefresh(View v){
        reLoad(mHandler);
    }

    public void fixListViewHeight(ListView listView) {
        // 如果没有设置数据适配器，则ListView没有子项，返回。
        ListAdapter listAdapter = listView.getAdapter();
        int totalHeight = 0;
        if (listAdapter == null) {
            return;
        }
        for (int index = 0, len = listAdapter.getCount(); index < len; index++) {
            View listViewItem = listAdapter.getView(index , null, listView);
            // 计算子项View 的宽高
            listViewItem.measure(0, 0);
            // 计算所有子项的高度和
            totalHeight += listViewItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // listView.getDividerHeight()获取子项间分隔符的高度
        // params.height设置ListView完全显示需要的高度
        params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     * 显示刷新的时候的等待进度条
     */
    private void showReflashDialog(String msg) {
        this.pd = new ProgressDialog(this);
        this.pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        this.pd.setCancelable(false);
        this.pd.setMessage(msg);
        this.pd.setMax(20);
        this.pd.show();
    }

    /**
     * 结束刷新的时候的等待进度条
     */
    private void stopReflashDialog() {
        if (this.pd != null) {
            pd.dismiss();
        }
    }
}
